package com.dd.cloud.common.utils;

import com.dd.cloud.common.config.common.DateConverterConfig;
import com.dd.cloud.common.exception.ZekeException;
import org.springframework.core.convert.converter.Converter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Description: String对象转换为LocalDateTime对象  // 类说明，在创建类时要填写
 * @ClassName: LocalDateTimeConverter    // 类名，会自动填充
 * @Author: weisn          // 创建者
 * @Date: 2022/9/27 16:12   // 时间
 * @Version: 1.0     // 版本
 */
public class LocalDateTimeConverter implements Converter<String, LocalDateTime> {

    private final DateTimeFormatter formatter;

    public LocalDateTimeConverter(String dateFormat) {
        this.formatter = DateTimeFormatter.ofPattern(dateFormat);
    }

    @Override
    public LocalDateTime convert(String source) {
        if (source == null || source.isEmpty()) {
            return null;
        }
        try {
            if (source.length() == DateConverterConfig.DEFAULT_DATE_PATTERN.length()) {
                source += " 00:00:00";
            }
            return LocalDateTime.parse(source, formatter);
        } catch (Exception e) {
            throw new ZekeException(400, "日期时间格式错误, 需要yyyy-MM-dd HH:mm:ss格式");
        }
    }
}
